﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RoutingDaemon.Utilities;
using RoutingDaemon.Entities;

namespace RoutingDaemon.ServerInterface.CommandHandlers
{
    class NEXTHOPCommandHandler : CommandHandlerBase
    {
        public override string HandleCommand(global::RoutingDaemon.ServerInterface.Commands.DaemonCommandBase command)
        {
            if (command is Commands.NEXTHOPCommand)
            {
                Commands.NEXTHOPCommand nextHopCommand = (Commands.NEXTHOPCommand)command;

                if (string.IsNullOrEmpty(nextHopCommand.Nickname))
                {
                    return "Error";
                }

                User user = new User()
                {
                    Nickname = nextHopCommand.Nickname
                };

                int nodeID = -1;
                int distance = -1;
                // Search for the user in the local node first.
                if (Backend.DaemonBackEnd.Instance.LocalNode.Users.Contains(user))
                {
                    distance = 0;
                    nodeID = Backend.DaemonBackEnd.Instance.LocalNode.NodeID;
                }
                else
                {
                    // Search for the user in the routing table
                    foreach (RoutingTableEntry tableEntry in Backend.DaemonBackEnd.Instance.RoutingTable)
                    {
                        if (tableEntry.Node.Users.Contains(user))
                        {
                            if (tableEntry.NextHop == null)
                                nodeID = tableEntry.Node.NodeID;
                            else
                                nodeID = tableEntry.NextHop.NodeID;
                            distance = tableEntry.Distance;
                        }
                    }

                    if (nodeID == -1 || distance == -1)
                    {
                        return Responses.GetResponse(ResponseCodes.None, string.Empty);
                    }
                }
                return Responses.GetResponse(ResponseCodes.NextHop_OK, new string[] { nodeID.ToString(), distance.ToString() });
            }
            else
            {
                throw new ArgumentException();
            }

        }
    }
}
